package controllers;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;

import javax.swing.JOptionPane;

import model.ComplaintModel;
import model.TaarifModel;
import model.TaarifRequestModel;
import view.ComplaintDetailsGUI;
import client.CliMessage;
import client.MailMessage;


	/**
	 * This Class is a Complaint Details Controller which  extends AbstractController implements IValidateInput
	 * @author Tal & Yuda
	 *
	 */

	public class ComplaintDetailsController extends AbstractController implements IValidateInput
	{	
				private ComplaintDetailsGUI ComplaintDetailsView;
				private ComplaintModel ComplaintModel;		
				private ArrayList<TaarifModel>  tarRequest;
				private String email;
				/**
				 * This is ComplaintDetailsController controller constructor.
				 * @param ComplaintDetailsView is a Complaint Details Window instance.
				 * @param ComplaintModel is a Complaint Model instance.
				 */
				public ComplaintDetailsController(ComplaintDetailsGUI ComplaintDetailsView, ComplaintModel complaintModel) 
				{
					super(ComplaintDetailsView,complaintModel);
					this.ComplaintDetailsView = ComplaintDetailsView;
					this.ComplaintModel = complaintModel;
				}
				
				/**
				 * This is setButtons method-this method add listeners to buttons in Complaint Details window -reply/Compensation.
				 * 
				 */
				
				public void setButtons(ComplaintModel Complaint)
				{
					
					ComplaintDetailsView.addReplyActionListener(new ReplyListener(Complaint));
				}
				
				@Override
				public boolean validateInput() 
				{
					
						if( (ComplaintDetailsView.getReply().equals("")))
						{
							
							ComplaintDetailsView.displayWrnMessage("You MUST enter Fields!!");
							
							return false;
						}
						
						if(ComplaintDetailsView.checkBoxPressed())
						{
							if(ComplaintDetailsView.getItemSelectedIndex()==0)
							{
                                   ComplaintDetailsView.displayWrnMessage("You Must To Choose Valid Package!!");
							
							    return false;
							}

						}
						
					return true;
					
				}
				/**
				 * This is SendMail method-send mail to customer for his Comp 
		         * @param String body, String email
				 */
				
				public void SendMail(String body,String email)
				{
					if (email!=null)
					{
					   MailMessage send = new MailMessage();
					
					
					send.sendMail(email,"Compensation ","You got a new "+body+"Subscrption, We Hope that you will Enjoy our Service ");
					}
			   }


				/**
				 * Inner class that handles when Reply Button Pressed, implements Action listener
				 * @author Tal
				 *
				 */
				
				class ReplyListener implements ActionListener
				{
					
					private ComplaintModel CompModel;
					
					public ReplyListener(ComplaintModel CompModel)
					{
						this.CompModel=CompModel;
					}
					
					@Override
					public void actionPerformed(ActionEvent arg0) 
					{
						boolean flag=true;
						
						if(!validateInput())
							return;
						
						if(!ComplaintDetailsView.checkBoxPressed())
							flag=false;
							
					   String reply=ComplaintDetailsView.getReply();
					   
                       int comid=CompModel.getComID();
                       int uid=CompModel.getCID();
						//insert reply to complaint id and change status in db
                       
						String updateQuary = "adu" + "UPDATE customer_complaints " +
		    					             " SET status = 1 "
		    					             + " WHERE comid = " + comid;
						
					
						
						 //send comp
						 
						  String updateQuary2 = "adu" + "UPDATE customer_complaints " +
		    					             " SET reply='" + reply
		    					             + "' WHERE comid = " + comid;
						  
						  sendToServer(updateQuary); 
                          sendToServer(updateQuary2);
                          
                          //give comp to customer
						  if(flag)
						  {
						     //init account deatils
						     int index=ComplaintDetailsView.getItemSelectedIndex();
						     int active=1;
						     int gid=tarRequest.get(index-1).getserviceID();
						     double balance_value=tarRequest.get(index-1).getoldPrice();
						     int balance;
						     String serviceName=tarRequest.get(index-1).getdescription();
						     System.out.println("comp:::::"+"index "+index+"service "+gid+"balance "+balance_value);
						     //photo packege or layers
						     if (gid==2)
						    	 balance=200;
						     else
						    	 balance=1;
						     
						     if (gid==5)
						    	  serviceName+="On Area 1"; 
						     
						     JOptionPane.showMessageDialog(null, "Customer Service Sent "+ serviceName +" to Customer !!! ", "Feedback Information", JOptionPane.INFORMATION_MESSAGE);
						     SendMail(serviceName,email);
			                ///charge account
			                        String insertQuery = "adu"	+"INSERT INTO customer_account "
                                                          	+"(uid,subscription_type,balance,balance_value,active) VALUES "
                                                          	+"("+ uid +"," + gid + "," + balance +","+ balance_value + ","+ active + ""+")";

			                        
					
			                        sendToServer(insertQuery);
			                        
			                    //enter to user groups    
			                        String insertQuery2 = "adu"	+"INSERT INTO user_groups "
					                    	+"(uid,gid) VALUES "
					                    	+"(" + uid + "," + gid + ")";
				
				
				                                 sendToServer(insertQuery2);
			                  
			                        
						  }       
						  else
							  JOptionPane.showMessageDialog(null, "Customer Service Sent Reply to Customer!!! ", "Feedback Information", JOptionPane.INFORMATION_MESSAGE);  
						  
						String searchQuery = "search"	+"SELECT cusComp.comid,cusComp.uid,u.fname,u.lname "
								+" FROM customer_complaints AS cusComp, user AS u"
                                +" WHERE cusComp.uid=u.uid AND cusComp.status=0 ";

                          
						
                           
                           
                         //activate the back button
                           ComplaintDetailsView.clickBackButton();
                           
                          
                         
                           sendToServer(searchQuery);
                           
					}
				}


				@Override
				public void handleDBRequestSuccess()
				{
					ComplaintDetailsView.displayWrnMessage("Reply Succesfully Enterd");
					
				}
			
				
				
				@Override
				public void handleDBSearchResult(CliMessage dbResult) 
				{	
					//get a list of all unhendled complaints
					ArrayList<HashMap<String, String>> srs = dbResult.getSrs();
					
					
					String fname = null;
					String lname = null;
					
					   Map<String, String> complaintTupple  = srs.get(0);	
					   
					if(complaintTupple.get("FNAME")!=null)
					{
					   System.out.println("com id:"+ComplaintModel.getComID()+""+"user id:"+ComplaintModel.getCID()+" "+"fname:"+complaintTupple.get("FNAME")+" "+"lname:"+complaintTupple.get("LNAME")+""+"details:"+complaintTupple.get("DETAILS")+""+"status"+complaintTupple.get("STATUS"));
					 //initialzie Complaint
					  ComplaintModel.setDetails(complaintTupple.get("DETAILS"));
					  ComplaintModel.setStatus(Integer.parseInt(complaintTupple.get("STATUS")));		
					  //initialize l/fname
					  fname=complaintTupple.get("FNAME");
					  lname=complaintTupple.get("LNAME");
					  email=complaintTupple.get("EMAIL"); 
					
					 int curruid= ComplaintModel.getCID();
					///set fields GUi
					ComplaintDetailsView.SetGenLabel("UID: "+String.valueOf(ComplaintModel.getCID()), ComplaintDetailsView.getUID());
					ComplaintDetailsView.SetGenLabel("fName: "+fname, ComplaintDetailsView.getfName());
					ComplaintDetailsView.SetGenLabel("lName: "+lname, ComplaintDetailsView.getlName());
					ComplaintDetailsView.SetGenLabel("Status: "+ComplaintModel.getStatusString(), ComplaintDetailsView.getStatus());
					ComplaintDetailsView.setComplaintDetArea(ComplaintModel.getDetails());
					
				
					//get the subscription to com....customer account
					String searchQuery2 = "search"	+"SELECT * "
                        	                        +" FROM taarif AS t,groups g"
                                                    +" WHERE  g.gid=t.serviceid AND g.type=1 AND t.serviceid NOT IN (SELECT c.subscription_type"
                                                    +" FROM customer_account AS c"
                                                    +" WHERE c.uid="+ curruid +"  AND c.active=1"
                                                    +" GROUP BY c.uid "+")" ;
                 
					
                        sendToServer(searchQuery2);
                        
                      //setButtons
    					setButtons(ComplaintModel);
				   }
				else	
				{
					//return service id
					int rows=srs.size();
					
					tarRequest=new ArrayList<TaarifModel>();
					for(int i=0;i<rows;i++)
					{
						Map<String, String> subList  = srs.get(i);	
						
						 //add Taarif to arraylist					
						System.out.println("service id:"+subList.get("SERVICEID")+" "+"disc:"+subList.get("DESCRIPTION")+" "+"price:"+subList.get("PRICE"));
						tarRequest.add(new TaarifModel(Integer.parseInt(subList.get("SERVICEID")),subList.get("DESCRIPTION"),Double.parseDouble(subList.get("PRICE")),0));
					}
					
					  //add data from db to combo
					ComplaintDetailsView.setArrayDescr(tarRequest);
					ComplaintDetailsView.setCombo();
					
						
				}
							
					
					
					//display main window
					ComplaintDetailsView.setVisible(true);	
				}

				@Override
				public void handleNullSearchResult() 
				{
					//ComplaintDetailsView.displayWrnMessage("Unhandle Complaint Not Found!!!");
					
				}



}
